package com.mayikt.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mayikt.entity.Category;
import com.mayikt.entity.CategoryExample;
import com.mayikt.mapper.CategoryMapper;
import com.mayikt.req.CategoryQueryReq;
import com.mayikt.req.CategorySaveReq;
import com.mayikt.resp.CategoryQueryResp;
import com.mayikt.resp.PageResp;
import com.mayikt.utils.CopyUtil;
import com.mayikt.utils.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private SnowFlake snowFlake;

    /**
     * 查询
     * @param categoryQueryReq
     * @return
     */
    public PageResp<CategoryQueryResp> list(CategoryQueryReq categoryQueryReq) {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();

        // 判断 name 条件是否为空
        if(!ObjectUtils.isEmpty(categoryQueryReq.getName())) {
            criteria.andNameLike("%" + categoryQueryReq.getName() + "%");
        }

        // 分页
        PageHelper.startPage(categoryQueryReq.getPage(), categoryQueryReq.getSize());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);

        // do 转 dto
        List<CategoryQueryResp> categoryResps = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        PageResp<CategoryQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(categoryResps);

        return pageResp;
    }

    /**
     * 查询所有分类
     * @return
     */
    public List<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        // 排序
        categoryExample.setOrderByClause("sort asc");

        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        // do 转 dto
        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        return list;
    }

    @Transactional
    public int save(CategorySaveReq categorySaveReq) {
        Category category = CopyUtil.copy(categorySaveReq, Category.class);
        int result = 0;
        if(ObjectUtils.isEmpty(categorySaveReq.getId())) {
            // 雪花算法 生成id
            category.setId(snowFlake.nextId());
            // 新增
            result = categoryMapper.insert(category);
        } else {
            // 更新
            result = categoryMapper.updateByPrimaryKey(category);
        }
        return result;
    }

    @Transactional
    public int delete(Long id) {
        return categoryMapper.deleteByPrimaryKey(id);
    }
}
